package com.nlp.visualization.service.impl;

import com.nlp.visualization.core.sentence.ISentenceService;
import com.nlp.visualization.core.sentence.SentenceType;
import com.nlp.visualization.core.sentence.SentenceUtils;
import com.nlp.visualization.pojo.NLP.sen.SentenceCoNLLWord;
import com.nlp.visualization.pojo.NLP.sen.SentenceEntity;
import com.nlp.visualization.service.IDataSentenceService;
import com.nlp.visualization.service.IFileService;
import com.nlp.visualization.utils.MD5Util;
import com.nlp.visualization.utils.PropertyUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 句子依存关系的服务实现类
 */
@Service
public class DataSentenceServiceImpl implements IDataSentenceService {

    Logger logger = LoggerFactory.getLogger(DataSentenceServiceImpl.class);

    @Autowired
    private ISentenceService sentenceService;

    @Autowired
    private IFileService fileService;

    SentenceType defaultType = SentenceType.HANLP_MaxEnt;


    @Override
    public File parseFile(File in, String savePath, SentenceType type) throws IOException {
        String commonDonwloadPath = PropertyUtil.getInstance("config").getProperty("download.common.path");
        // 检查下载目录
        File uploadDir = new File(savePath + "/" + commonDonwloadPath);
        if (!uploadDir.isDirectory()) {
            // 如果不存在，创建文件夹
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
        }
        // 检查下载子目录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String ymd = sdf.format(new Date());
        commonDonwloadPath += "/" + ymd + "/";
        File dirFile = new File(savePath + "/" + commonDonwloadPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        //生成一个分词后的文件
        File out = new File(savePath + "/" + commonDonwloadPath + "/" + MD5Util.MD5(in.getName()) + ".txt");

        //读取原文件，并分词，保存到out中
        String inFileString = FileUtils.readFileToString(in);
//        List<String> outStringList = segmentService.executeSeg(inFileString, segmentType, filter);
        String outString = null;
        try {
            List<SentenceCoNLLWord> words = sentenceService.excuteSentenceDependencyAnalyze(inFileString, defaultType);
            for (SentenceCoNLLWord word : words) {
                outString += word.toString()+"\n";
            }
        } catch (Exception e) {
            logger.error("分析句法异常");
            e.printStackTrace();
        }
        FileUtils.writeStringToFile(out, outString, "utf-8");

        return out;
    }

    /**
     * 单句句法分析
     *
     * @param text
     * @param type 调用的方法
     * @return
     */
    @Override
    public SentenceEntity parseSingle(String text, SentenceType type) {

        List<SentenceCoNLLWord> wordList;
        SentenceEntity entity = new SentenceEntity();
        List items = new ArrayList();
        //写入返回实体
        entity.setText(text);
        try {
            //调用句法分析
            wordList = sentenceService.excuteSentenceDependencyAnalyze(text, type);
            for (SentenceCoNLLWord word : wordList) {
                SentenceEntity.ItemsBean itemsBean = new SentenceEntity.ItemsBean();
                itemsBean.setDeprel(SentenceUtils.getRelationName(word.getDEPREL()));
                itemsBean.setDetail(word.getDEPREL());
                itemsBean.setHead(word.getHEAD_ID());
                itemsBean.setId(word.getID() + "");
                itemsBean.setPos(word.getPOSTAG());
                itemsBean.setWord(word.getLEMMA());
                items.add(itemsBean);
            }
            entity.setItems(items);
            return entity;
        } catch (Exception e) {
            logger.error("单句句法分析异常");
            e.printStackTrace();
        }

        //确保有结果返回
        entity.setText(text);
        entity.setItems(items);
        return entity;
    }

    /**
     * 批量句法分析
     *
     * @param texts
     * @param type
     * @return
     */
    @Override
    public List<SentenceEntity> parseMutil(List<String> texts, SentenceType type) {
        List resList = new ArrayList();
        for (String text : texts) {
            SentenceEntity entity = parseSingle(text, type);
            resList.add(entity);
        }
        return resList;
    }

    /**
     * 直接输出的句法分析结果
     *
     * @param texts
     * @param type
     * @return
     */
    @Override
    public String parse2Text(List<String> texts, SentenceType type) {
        String res = "";
        for (String text : texts) {
            SentenceEntity entity = parseSingle(text, type);
            res += entity + "\n\n";
        }
        return res;
    }
}
